<template>
  <div class="expert-chat">
    <el-container>
      <el-header>
        <div class="header-content">
          <div class="header-left">
            <el-button type="primary" @click="router.push('/expert-qa')">
              <el-icon><ArrowLeft /></el-icon>
              返回专家列表
            </el-button>
          </div>
          <div class="header-center">
            <div class="expert-info" v-if="expertInfo">
              <el-avatar 
                :size="40" 
                :src="expertInfo.imageUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
              />
              <h3>{{ expertInfo.callName || expertInfo.userName }}</h3>
              <el-tag type="success" size="small">在线</el-tag>
            </div>
          </div>
          <div class="header-right"></div>
        </div>
      </el-header>
      <el-main>
        <div class="chat-container" ref="chatContainer">
          <div class="messages" ref="messagesContainer">
            <div 
              v-for="message in messages" 
              :key="message.id" 
              :class="['message', message.fromUserId === currentUserId ? 'message-right' : 'message-left']"
            >
              <el-avatar 
                :size="40" 
                :src="message.fromUserId === currentUserId ? currentUserAvatar : expertInfo?.imageUrl"
              />
              <div class="message-content">
                <template v-if="message.messageType === 'image'">
                  <el-image 
                    :src="message.content" 
                    class="message-image" 
                    alt="图片消息"
                    :preview-src-list="[message.content]"
                    :initial-index="0"
                    fit="cover"
                    :preview-teleported="true"
                  />
                </template>
                <template v-else>
                  <p class="message-text">{{ message.content }}</p>
                </template>
                <span class="message-time">{{ formatTime(message.createTime) }}</span>
              </div>
            </div>
          </div>
        </div>
      </el-main>
      <el-footer height="auto">
        <div class="input-area">
          <el-input
            v-model="messageInput"
            type="textarea"
            :rows="3"
            placeholder="输入消息..."
            @keyup.enter.native.exact="sendMessage"
          />
          <div class="button-group">
            <el-upload
              class="upload-button"
              action="#"
              :show-file-list="false"
              :auto-upload="false"
              accept="image/*"
              @change="handleImageSelect"
            >
              <el-button type="primary">
                <el-icon><Picture /></el-icon>
                照片
              </el-button>
            </el-upload>
            <el-button type="primary" @click="sendMessage" :disabled="!messageInput.trim()">
              发送
            </el-button>
          </div>
        </div>
      </el-footer>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Picture } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const expertId = route.params.expertId
const currentUserId = userStore.userInfo?.userId
const currentUserAvatar = userStore.userInfo?.imageUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

const expertInfo = ref(null)
const messages = ref([])
const messageInput = ref('')
const chatContainer = ref(null)
const messagesContainer = ref(null)
let ws = null
let reconnectCount = 0
const MAX_RECONNECT_ATTEMPTS = 5
let reconnectTimeout = null
let isConnecting = false

// 加载专家信息
const loadExpertInfo = async () => {
  try {
    const response = await request({
      url: `/api/chat/experts/${expertId}`,
      method: 'get'
    })
    
    console.log('获取专家信息响应:', response)
    
    // 检查是否是响应拦截器的数据格式
    if (response?.code === 200) {
      if (response.data) {
        expertInfo.value = response.data
        console.log('设置专家信息:', expertInfo.value)
      } else {
        ElMessage.error('专家信息为空')
      }
    } else if (response?.userId) {
      // 如果直接返回的是专家信息对象
      expertInfo.value = response
      console.log('直接设置专家信息:', expertInfo.value)
    } else {
      ElMessage.error('获取专家信息失败')
    }
  } catch (error) {
    console.error('获取专家信息失败:', error)
    ElMessage.error('获取专家信息失败')
  }
}

// 加载历史消息
const loadHistoryMessages = async () => {
  try {
    const response = await request({
      url: `/api/chat/history/${expertId}`,
      method: 'get',
      params: { userId: currentUserId }
    })
    
    console.log('获取历史消息响应:', response)
    
    let historyMessages = []
    if (response?.code === 200) {
      historyMessages = response.data || []
    } else if (Array.isArray(response)) {
      historyMessages = response
    } else {
      ElMessage.error('获取历史消息失败')
      return
    }

    // 处理每条消息的类型
    messages.value = historyMessages.map(msg => ({
      ...msg,
      messageType: msg.messageType || (
        msg.content && msg.content.startsWith('http') && 
        (msg.content.endsWith('.png') || 
         msg.content.endsWith('.jpg') || 
         msg.content.endsWith('.jpeg') || 
         msg.content.endsWith('.gif') || 
         msg.content.endsWith('.webp')) ? 'image' : 'text'
      )
    }))

    console.log('设置历史消息:', messages.value)
    if (historyMessages.length === 0) {
      ElMessage.info('暂无聊天记录')
    }
    await nextTick()
    scrollToBottom()
  } catch (error) {
    console.error('获取历史消息失败:', error)
    ElMessage.error('获取历史消息失败')
  }
}

// 初始化WebSocket连接
const initWebSocket = () => {
  if (isConnecting) {
    console.log('WebSocket连接正在进行中，跳过重连')
    return
  }

  if (reconnectCount >= MAX_RECONNECT_ATTEMPTS) {
    console.log('达到最大重连次数，停止重连')
    ElMessage.error('连接失败，请刷新页面重试')
    return
  }

  isConnecting = true
  const wsUrl = `ws://localhost:8888/ws/chat/${currentUserId}/${expertId}`
  console.log(`正在建立WebSocket连接 (第${reconnectCount + 1}次尝试):`, wsUrl)
  console.log('连接参数 - 当前用户ID:', currentUserId, '专家ID:', expertId)
  
  try {
    if (ws) {
      console.log('关闭现有WebSocket连接')
      ws.close(1000, '主动关闭以重新连接')
    }

    ws = new WebSocket(wsUrl)

    // 设置连接超时
    const connectionTimeout = setTimeout(() => {
      if (ws.readyState === WebSocket.CONNECTING) {
        console.log('连接超时，关闭连接')
        ws.close()
        isConnecting = false
        handleReconnect()
      }
    }, 5000)

    ws.onopen = () => {
      console.log('WebSocket连接已建立 - 用户ID:', currentUserId)
      clearTimeout(connectionTimeout)
      isConnecting = false
      reconnectCount = 0 // 重置重连次数
      
      // 发送一个更详细的初始化消息
      const initMessage = {
        type: 'init',
        fromUserId: currentUserId,
        toUserId: expertId,
        timestamp: new Date().getTime(),
        userType: 'user',
        sessionId: localStorage.getItem('sessionId') || '',
        token: localStorage.getItem('token') || '',
        metadata: {
          userAgent: navigator.userAgent,
          timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
          reconnectCount: reconnectCount
        }
      }
      console.log('发送初始化消息:', initMessage)
      ws.send(JSON.stringify(initMessage))

      // 设置定期发送心跳
      startHeartbeat()
    }

    ws.onmessage = (event) => {
      try {
        const message = JSON.parse(event.data)
        console.log('收到消息:', message)
        
        if (message.type === 'init') {
          console.log('收到初始化响应:', message)
          if (message.success === false) {
            console.error('初始化失败:', message.message)
            ElMessage.error(message.message || '连接初始化失败')
            ws.close(1000, '初始化失败')
            return
          }
          // 保存服务器返回的会话信息
          if (message.sessionId) {
            localStorage.setItem('sessionId', message.sessionId)
          }
          console.log('初始化成功')
          return
        }

        if (message.type === 'heartbeat') {
          console.log('收到心跳响应')
          return
        }
        
        if (message.type === 'error') {
          console.error('收到错误消息:', message)
          if (message.code === 'HOT_RELOAD') {
            console.log('检测到服务器热部署，等待重连')
            handleHotReload()
            return
          }
          ElMessage.error(message.message || '发生错误')
          if (message.code === 'SESSION_INVALID') {
            ws.close(1000, '会话无效')
            router.push('/expert-qa')
          }
          return
        }

        if (message.type === 'chat') {
          // 检查消息内容是否是图片URL格式
          if (message.content && (
              message.content.startsWith('http') && 
              (message.content.endsWith('.png') || 
               message.content.endsWith('.jpg') || 
               message.content.endsWith('.jpeg') || 
               message.content.endsWith('.gif') || 
               message.content.endsWith('.webp'))
          )) {
            message.messageType = 'image'
          }
          
          messages.value.push({
            ...message,
            id: message.id || Date.now(),
            messageType: message.messageType || (
              message.content && message.content.startsWith('http') && 
              (message.content.endsWith('.png') || 
               message.content.endsWith('.jpg') || 
               message.content.endsWith('.jpeg') || 
               message.content.endsWith('.gif') || 
               message.content.endsWith('.webp')) ? 'image' : 'text'
            )
          })
          nextTick(() => {
            scrollToBottom()
          })
        }
      } catch (error) {
        console.error('处理消息时发生错误:', error)
      }
    }

    ws.onerror = (error) => {
      console.error('WebSocket错误:', error)
      clearTimeout(connectionTimeout)
      isConnecting = false
      stopHeartbeat()
      handleReconnect()
    }

    ws.onclose = (event) => {
      console.log('WebSocket连接已关闭 - 代码:', event.code, '原因:', event.reason, '是否正常关闭:', event.wasClean)
      clearTimeout(connectionTimeout)
      isConnecting = false
      stopHeartbeat()
      
      if (event.code === 1011) {
        console.log('服务器内部错误，可能是热部署导致的')
        handleHotReload()
      } else if (event.code !== 1000 && event.code !== 1001) {
        // 1000: 正常关闭, 1001: 离开页面
        handleReconnect()
      }
    }
  } catch (error) {
    console.error('建立WebSocket连接失败:', error)
    isConnecting = false
    stopHeartbeat()
    handleReconnect()
  }
}

// 心跳相关变量和函数
let heartbeatInterval = null
const HEARTBEAT_INTERVAL = 30000 // 30秒发送一次心跳

const startHeartbeat = () => {
  if (heartbeatInterval) {
    clearInterval(heartbeatInterval)
  }
  
  heartbeatInterval = setInterval(() => {
    if (ws && ws.readyState === WebSocket.OPEN) {
      const heartbeat = {
        type: 'heartbeat',
        fromUserId: currentUserId,
        timestamp: new Date().getTime()
      }
      console.log('发送心跳:', heartbeat)
      ws.send(JSON.stringify(heartbeat))
    }
  }, HEARTBEAT_INTERVAL)
}

const stopHeartbeat = () => {
  if (heartbeatInterval) {
    clearInterval(heartbeatInterval)
    heartbeatInterval = null
  }
}

// 处理热部署重连
const handleHotReload = () => {
  console.log('等待服务器重启完成...')
  // 等待一段时间再重连，给服务器重启留出时间
  setTimeout(() => {
    console.log('尝试重新连接服务器')
    reconnectCount = 0 // 重置重连次数，因为这是热部署导致的
    initWebSocket()
  }, 5000) // 等待5秒
}

// 处理重连
const handleReconnect = () => {
  if (reconnectCount >= MAX_RECONNECT_ATTEMPTS) {
    console.log('达到最大重连次数，停止重连')
    ElMessage.error('连接失败，请刷新页面重试')
    return
  }

  reconnectCount++
  const delay = Math.min(1000 * Math.pow(2, reconnectCount), 10000) // 指数退避，最大10秒
  console.log(`将在 ${delay/1000} 秒后进行第 ${reconnectCount} 次重连`)
  
  if (reconnectTimeout) {
    clearTimeout(reconnectTimeout)
  }
  
  reconnectTimeout = setTimeout(() => {
    if (!isConnecting) {
      initWebSocket()
    }
  }, delay)
}

// 发送消息
const sendMessage = () => {
  if (!messageInput.value.trim()) return
  
  const message = {
    type: 'chat',
    fromUserId: currentUserId,
    toUserId: expertId,
    content: messageInput.value.trim(),
    createTime: new Date().toISOString(),
    timestamp: new Date().getTime(),
    id: Date.now()
  }

  if (ws && ws.readyState === WebSocket.OPEN) {
    try {
      console.log('发送消息:', message)
      ws.send(JSON.stringify(message))
      // 添加到本地消息列表
      messages.value.push(message)
      messageInput.value = ''
      nextTick(() => {
        scrollToBottom()
      })
    } catch (error) {
      console.error('发送消息失败:', error)
      ElMessage.error('发送消息失败，正在重新连接...')
      handleReconnect()
    }
  } else {
    console.log('WebSocket未连接，状态:', ws?.readyState)
    ElMessage.error('聊天连接已断开，正在重新连接...')
    handleReconnect()
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 格式化时间
const formatTime = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 处理图片选择
const handleImageSelect = async (file) => {
  const selectedFile = file.raw
  if (!selectedFile) {
    console.warn('未选择文件')
    return
  }

  try {
    // 检查文件类型
    console.log('选择的文件类型:', selectedFile.type)
    if (!selectedFile.type.startsWith('image/')) {
      ElMessage.error('请选择图片文件')
      return
    }

    // 检查文件大小（限制为5MB）
    const maxSize = 5 * 1024 * 1024
    console.log('文件大小:', selectedFile.size, 'bytes')
    if (selectedFile.size > maxSize) {
      ElMessage.error('图片大小不能超过5MB')
      return
    }

    // 创建 FormData 对象
    const formData = new FormData()
    formData.append('image', selectedFile)

    try {
      console.log('开始上传图片，文件信息:', {
        name: selectedFile.name,
        type: selectedFile.type,
        size: selectedFile.size
      })

      // 上传图片到阿里云OSS
      const response = await request({
        url: '/api/chat/upload/image',
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        timeout: 60000  // 增加超时时间到60秒
      })

      console.log('上传响应:', response)

      // 处理响应数据
      let imageUrl
      if (typeof response === 'string') {
        // 直接返回URL的情况
        imageUrl = response
      } else if (response?.code === 200 && response.data) {
        // 标准响应格式的情况
        imageUrl = response.data
      } else {
        console.error('上传失败，响应:', response)
        throw new Error(response?.message || '图片上传失败')
      }

      if (imageUrl) {
        console.log('上传成功，图片URL:', imageUrl)
        // 发送包含图片URL的消息
        sendImageMessage(imageUrl)
      } else {
        throw new Error('未获取到图片URL')
      }
    } catch (error) {
      console.error('图片上传失败，详细错误:', error)
      if (error.response) {
        console.error('错误响应:', error.response)
      }
      ElMessage.error(error.message || '图片上传失败')
    }
  } catch (error) {
    console.error('图片处理失败:', error)
    ElMessage.error('图片处理失败')
  }
}

// 发送图片消息
const sendImageMessage = (imageUrl) => {
  const message = {
    type: 'chat',
    fromUserId: currentUserId,
    toUserId: expertId,
    content: imageUrl,
    createTime: new Date().toISOString(),
    timestamp: new Date().getTime(),
    id: Date.now(),
    messageType: 'image'
  }

  if (ws && ws.readyState === WebSocket.OPEN) {
    try {
      console.log('发送图片消息')
      ws.send(JSON.stringify(message))
      // 添加到本地消息列表
      messages.value.push(message)
      nextTick(() => {
        scrollToBottom()
      })
    } catch (error) {
      console.error('发送图片消息失败:', error)
      ElMessage.error('发送图片消息失败，正在重新连接...')
      handleReconnect()
    }
  } else {
    console.log('WebSocket未连接，状态:', ws?.readyState)
    ElMessage.error('聊天连接已断开，正在重新连接...')
    handleReconnect()
  }
}

onMounted(async () => {
  if (!currentUserId) {
    ElMessage.error('请先登录')
    router.push('/login')
    return
  }

  await loadExpertInfo()
  await loadHistoryMessages()
  initWebSocket()

  // 页面关闭前关闭WebSocket连接
  window.addEventListener('beforeunload', () => {
    if (reconnectTimeout) {
      clearTimeout(reconnectTimeout)
    }
    if (ws) {
      ws.close(1000, '用户离开页面')
    }
  })
})

onUnmounted(() => {
  if (reconnectTimeout) {
    clearTimeout(reconnectTimeout)
  }
  stopHeartbeat()
  if (ws) {
    ws.close(1000, '组件卸载')
  }
})
</script>

<style scoped>
.expert-chat {
  height: 100vh;
  background-color: #f5f7fa;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.header-center {
  flex: 1;
  display: flex;
  justify-content: center;
}

.expert-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.expert-info h3 {
  margin: 0;
  font-size: 16px;
}

.chat-container {
  height: calc(100vh - 180px);
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
  gap: 10px;
}

.message-left {
  flex-direction: row;
}

.message-right {
  flex-direction: row-reverse;
}

.message-content {
  max-width: 60%;
}

.message-text {
  margin: 0;
  padding: 10px 15px;
  border-radius: 8px;
  font-size: 14px;
  line-height: 1.4;
}

.message-left .message-text {
  background-color: #f4f4f4;
}

.message-right .message-text {
  background-color: #e3f2fd;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  display: block;
}

.message-left .message-time {
  text-align: left;
}

.message-right .message-time {
  text-align: right;
}

.input-area {
  padding: 20px;
  background-color: #fff;
  border-top: 1px solid #eee;
  display: flex;
  gap: 10px;
}

.input-area .el-input {
  flex: 1;
}

.button-group {
  display: flex;
  gap: 10px;
  align-items: flex-end;
}

.upload-button {
  margin-bottom: 2px;
}

.upload-button .el-button {
  padding: 12px;
  height: 40px;
}

.el-footer {
  padding: 0;
}

.message-image {
  max-width: 200px;
  max-height: 200px;
  border-radius: 8px;
  cursor: pointer;
}
</style> 